package com.aigao.golf.common

import com.aigao.golf.exts.validJson
import org.springframework.web.util.HtmlUtils
import org.springframework.web.util.JavaScriptUtils

import java.beans.PropertyEditorSupport

/**
 * 类型转化类,防止跨脚本攻击，往web页面注入html代码或者script代码
 *
 * @author rankai
 * createTime 2017-04-2017/4/20 14:47
 */
class StringEscapeEditor : PropertyEditorSupport {
    /**
     * 编码HTML
     */
    private var escapeHTML: Boolean = false
    /**
     * 编码JavaScript
     */
    private var escapeJavaScript: Boolean = false
    /**
     * 过滤json
     */
    private var escapeJson: Boolean = false

    constructor() : super() {}

    constructor(escapeJson: Boolean, escapeHTML: Boolean, escapeJavaScript: Boolean) : super() {
        this.escapeJson = escapeJson
        this.escapeHTML = escapeHTML
        this.escapeJavaScript = escapeJavaScript
    }

    override fun getAsText(): String {
        val value = value
        return value?.toString() ?: ""
    }

    override fun setAsText(text: String?) {
        if (text == null) {
            value = null
        } else {
            if (escapeJson && text.validJson()) {
                value = text
            } else {
                var value: String = text
                if (escapeHTML) {
                    value = HtmlUtils.htmlEscape(value)
                }
                if (escapeJavaScript) {
                    value = JavaScriptUtils.javaScriptEscape(value)
                }
                setValue(value)
            }
        }
    }
}
